package com.qianxx.view.xrecyclerview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;

/**
 * Created by Administrator on 2017/6/16.
 */
public class LinearLoading extends View {

    private static final float SCALE = 1.0f;

    private Paint mPaint;

    private int[] delays = new int[]{100, 200, 300, 400, 500};
    private float[] scaleFloats = new float[]{SCALE, SCALE, SCALE, SCALE, SCALE};
    private ArrayList<ValueAnimator> animators = new ArrayList<>();

    public LinearLoading(Context context) {
        this(context, null);
    }

    public LinearLoading(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LinearLoading(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#6B7886"));
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float translateX = getWidth() / 11;
        float translateY = getHeight() / 2;
        for (int i = 0; i < 5; i++) {
            canvas.save();
            canvas.translate((2 + i * 2) * translateX - translateX / 2, translateY);
            canvas.scale(SCALE, scaleFloats[i]);
            RectF rectF = new RectF(-translateX / 2, -getHeight() / 2.5f, translateX / 2, getHeight() / 2.5f);
            canvas.drawRoundRect(rectF, 5, 5, mPaint);
            canvas.restore();
        }
    }

    public void showLoading() {
        if (getVisibility() == VISIBLE) {
            return;
        }

        setVisibility(VISIBLE);
        for (int i = 0; i < 5; i++) {
            final int index = i;

            ValueAnimator scale = ValueAnimator.ofFloat(1, 0.4f, 1);

            scale.setDuration(1000);
            scale.setRepeatCount(-1);
            scale.setStartDelay(delays[i]);

            scale.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    scaleFloats[index] = (float) animation.getAnimatedValue();
                    postInvalidate();
                }
            });

            scale.start();
            animators.add(scale);
        }
    }

    public void hideLoading() {
        for (ValueAnimator animator : animators) {
            animator.removeAllUpdateListeners();
            animator.cancel();
        }
        setVisibility(GONE);
    }
}
